package com.zl.boke.config.handler;

/**
 * @author zhanglei2
 * @since 2020/1/12 16:25
 */

import groovy.transform.AnnotationCollector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * 后端控制器自定义error异常处理器
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    //设置日志打印输出
   private final Logger logger = LoggerFactory.getLogger(this.getClass());
   @ExceptionHandler(Exception.class)
   public ModelAndView exceptionHander(HttpServletRequest request,Exception e) throws Exception{
       //输出日志信息请求的url,和异常信息
       logger.error("Request URL : {} , Exception : {}",request.getRequestURI(),e);
       //判断是否是自定义的error异常状态
       if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
       }
       //设置url和exception返回到前端error页面
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.addObject("url",request.getRequestURI());
       modelAndView.addObject("exception",e);
       modelAndView.setViewName("/error/error");
       return modelAndView;
   }
}
